/**
 * 
 */
package ru.olympus.antonyhands.ao.server.util;

import java.util.ArrayList;
import java.util.List;

import ru.olympus.antonyhands.ao.client.widgets.TreeTable.TreeTableDataSourceRow;
import ru.olympus.antonyhands.ao.server.item.Item;
import ru.olympus.antonyhands.ao.server.item.ItemQuantityPair;
import ru.olympus.antonyhands.ao.shared.util.LongUtilities;
import ru.olympus.antonyhands.ao.shared.util.StringPair;
import ru.olympus.antonyhands.ao.shared.util.StringUtilities;

/**
 * @author AntonyHands
 * @since 09.03.2012
 */
public class TreeTableDSHelper {
	
	private static final String BOLD_FONT_STYLE = "boldFont";

	public static TreeTableDataSourceRow createHeader()
	{
		TreeTableDataSourceRow res = new TreeTableDataSourceRow();
		List<StringPair> cells = new ArrayList<StringPair>();
		cells.add(new StringPair("Наименование", BOLD_FONT_STYLE));
		cells.add(new StringPair("Фикс цена", BOLD_FONT_STYLE));
		cells.add(new StringPair("Крафт цена", BOLD_FONT_STYLE));
		cells.add(new StringPair("Рынок цена", BOLD_FONT_STYLE));
		cells.add(new StringPair("Количество", BOLD_FONT_STYLE));
		res.setCells(cells);
		return res;
	}
	
	public static TreeTableDataSourceRow createRowForItem(Item item, int level, Long quantity)
	{
		TreeTableDataSourceRow res = new TreeTableDataSourceRow();
		
		Long fixedPrice = item.getFixedPrice();
		Long craftPrice = item.getCraftPrice();
		Long marketPrice = item.getMarketPrice();
		Long bestPrice = item.getBestPrice();
		
		List<StringPair> cells = new ArrayList<StringPair>();
		cells.add(new StringPair(getTabulation(level) + item.getTitle(), ""));
		cells.add(priceWithStyle(fixedPrice, bestPrice));
		cells.add(priceWithStyle(craftPrice, bestPrice));
		cells.add(priceWithStyle(marketPrice, bestPrice));
		cells.add(new StringPair(StringUtilities.longToString(quantity), ""));
		res.setCells(cells);

		res.setOpened(LongUtilities.equals(craftPrice, bestPrice));

		if (item.getCraftInfo() != null)
		{
			List<TreeTableDataSourceRow> childrenRows = new ArrayList<TreeTableDataSourceRow>();
			for (ItemQuantityPair pair : item.getCraftInfo().listInputItemsData())
				childrenRows.add(createRowForItem(pair.getKey(), level + 1, pair.getValue()));
			res.setChildRows(childrenRows);
		}
		return res;
	}
	
	private static StringPair priceWithStyle(Long price, Long bestPrice)
	{
		StringPair sp = new StringPair();
		sp.setKey(StringUtilities.longToString(price));
		if (LongUtilities.equals(price, bestPrice))
		{
			sp.setKey("<b>" + sp.getKey() + "</b>");
			sp.setValue(BOLD_FONT_STYLE);
		}
		else
			sp.setValue("");
		return sp;
	}

	private static String getTabulation(int level)
	{
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < level; i++)
			sb.append("&nbsp;&nbsp;&nbsp;");
		return sb.toString();
	}
}
